{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9f96ce0c",
   "metadata": {},
   "source": [
    "# Pandas\n",
    "\n",
    "## 导入"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5225aa03",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0566a56",
   "metadata": {},
   "source": [
    "## 两种核心对象\n",
    "\n",
    "- `Series`: 保存任何类型数据的一维标记数组，例如整数、字符串、Python 对象等\n",
    "- `DataFrame`: 一种二维数据结构，用于保存二维数组或具有行和列的表等数据。\n",
    "\n",
    "## 创建实例对象"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3faa49ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    1.0\n",
      "1    3.0\n",
      "2    5.0\n",
      "3    NaN\n",
      "4    6.0\n",
      "5    8.0\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 一维标记数组series\n",
    "s = pd.Series([1, 3, 5, np.nan, 6, 8])\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0a413907",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',\n",
      "               '2013-01-05', '2013-01-06'],\n",
      "              dtype='datetime64[ns]', freq='D')\n",
      "                   A         B         C         D\n",
      "2013-01-01 -1.593051  2.214765  0.835041  0.310084\n",
      "2013-01-02  0.711600  0.492788  0.830289  1.179015\n",
      "2013-01-03 -0.174396  1.200618 -0.320375  0.132684\n",
      "2013-01-04  0.125475  0.540160 -0.412453  0.325969\n",
      "2013-01-05  0.529611  0.157162  0.141519  0.574031\n",
      "2013-01-06  0.022487 -0.105461  1.160064 -0.689046\n"
     ]
    }
   ],
   "source": [
    "# DataFrame对象\n",
    "dates = pd.date_range(\"20130101\", periods=6)\n",
    "print(dates)\n",
    "df = pd.DataFrame(\n",
    "    np.random.randn(6, 4), # 6行4列随机浮点数数组\n",
    "    index=dates, # 行标签\n",
    "    columns=list(\"ABCD\") # 列标签\n",
    ")\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "461d2391",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     A          B    C  D      E    F\n",
      "0  1.0 2013-01-02  1.0  3   test  foo\n",
      "1  1.0 2013-01-02  1.0  3  train  foo\n",
      "2  1.0 2013-01-02  1.0  3   test  foo\n",
      "3  1.0 2013-01-02  1.0  3  train  foo\n",
      "\n",
      "A          float64\n",
      "B    datetime64[s]\n",
      "C          float32\n",
      "D            int32\n",
      "E         category\n",
      "F           object\n",
      "dtype: object\n"
     ]
    }
   ],
   "source": [
    "# 通过字典创建DataFrame\n",
    "df2 = pd.DataFrame(\n",
    "    {\n",
    "        \"A\": 1.0,\n",
    "        \"B\": pd.Timestamp(\"20130102\"),\n",
    "        \"C\": pd.Series(1, index=list(range(4)), dtype=\"float32\"),\n",
    "        \"D\": np.array([3] * 4, dtype=\"int32\"),\n",
    "        \"E\": pd.Categorical([\"test\", \"train\", \"test\", \"train\"]),\n",
    "        \"F\": \"foo\",\n",
    "    }\n",
    ")\n",
    "print(df2)\n",
    "print()\n",
    "\n",
    "# DataFrame每列的数据类型可以不同，同一列的数据类型必须相同\n",
    "print(df2.dtypes)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f62845c",
   "metadata": {},
   "source": [
    "## 查看数据\n",
    "\n",
    "- DataFrame.head() 从上到下查看\n",
    "- DataFrame.tail() 从下到上查看\n",
    "- DataFrame.index 查看行标签\n",
    "- DataFrame.columns 查看列标签\n",
    "- DataFrame.describe() 数据的简要汇总\n",
    "    - count：非缺失值的数量。表示该列有多少个有效的数据（没有 NaN 等缺失值）。\n",
    "    - mean：均值。即该列所有数值的平均值。\n",
    "    - std：标准差。反映该列数据的离散程度，标准差越大，数据的波动越大。\n",
    "    - min：最小值。该列中的最小数值。\n",
    "    - 25%：第一四分位数（Q1）。将数据从小到大排序后，处于 25% 位置的数值。\n",
    "    - 50%：第二四分位数（Q2），也就是中位数。将数据从小到大排序后，处于 - 50% 位置的数值，反映数据的中间水平。\n",
    "    - 75%：第三四分位数（Q3）。将数据从小到大排序后，处于 75% 位置的数值。\n",
    "    - max：最大值。该列中的最大数值。\n",
    "- DataFrame.T 转置\n",
    "- DataFrame.sort_index() 通过axis重新排列\n",
    "- DataFrame.sort_values() 通过值重新排列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b4744574",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     A          B    C  D      E    F\n",
      "0  1.0 2013-01-02  1.0  3   test  foo\n",
      "1  1.0 2013-01-02  1.0  3  train  foo\n",
      "     A          B    C  D      E    F\n",
      "2  1.0 2013-01-02  1.0  3   test  foo\n",
      "3  1.0 2013-01-02  1.0  3  train  foo\n"
     ]
    }
   ],
   "source": [
    "# 查看前2行\n",
    "print(df2.head(2))\n",
    "\n",
    "# 查看后2行\n",
    "print(df2.tail(2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "029500e6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   A         B         C         D\n",
      "2013-01-01 -1.593051  2.214765  0.835041  0.310084\n",
      "2013-01-02  0.711600  0.492788  0.830289  1.179015\n",
      "2013-01-03 -0.174396  1.200618 -0.320375  0.132684\n",
      "2013-01-04  0.125475  0.540160 -0.412453  0.325969\n",
      "2013-01-05  0.529611  0.157162  0.141519  0.574031\n",
      "2013-01-06  0.022487 -0.105461  1.160064 -0.689046\n",
      "DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',\n",
      "               '2013-01-05', '2013-01-06'],\n",
      "              dtype='datetime64[ns]', freq='D')\n",
      "Index(['A', 'B', 'C', 'D'], dtype='object')\n",
      "[[-1.59305079  2.21476519  0.83504104  0.3100843 ]\n",
      " [ 0.71160002  0.4927876   0.83028891  1.17901532]\n",
      " [-0.17439618  1.20061803 -0.32037494  0.13268379]\n",
      " [ 0.12547544  0.54015979 -0.41245284  0.32596923]\n",
      " [ 0.52961061  0.1571623   0.14151866  0.57403125]\n",
      " [ 0.02248657 -0.10546106  1.1600641  -0.68904619]]\n"
     ]
    }
   ],
   "source": [
    "print(df)\n",
    "\n",
    "# 查看行标签\n",
    "print(df.index)\n",
    "\n",
    "# 查看列标签\n",
    "print(df.columns)\n",
    "\n",
    "# 转换为数组\n",
    "print(df.to_numpy())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fea79854",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   A         B         C         D\n",
      "2013-01-01 -1.593051  2.214765  0.835041  0.310084\n",
      "2013-01-02  0.711600  0.492788  0.830289  1.179015\n",
      "2013-01-03 -0.174396  1.200618 -0.320375  0.132684\n",
      "2013-01-04  0.125475  0.540160 -0.412453  0.325969\n",
      "2013-01-05  0.529611  0.157162  0.141519  0.574031\n",
      "2013-01-06  0.022487 -0.105461  1.160064 -0.689046\n",
      "              A         B         C         D\n",
      "count  6.000000  6.000000  6.000000  6.000000\n",
      "mean  -0.063046  0.750005  0.372347  0.305456\n",
      "std    0.818228  0.841672  0.662322  0.609026\n",
      "min   -1.593051 -0.105461 -0.412453 -0.689046\n",
      "25%   -0.125175  0.241069 -0.204902  0.177034\n",
      "50%    0.073981  0.516474  0.485904  0.318027\n",
      "75%    0.428577  1.035503  0.833853  0.512016\n",
      "max    0.711600  2.214765  1.160064  1.179015\n"
     ]
    }
   ],
   "source": [
    "print(df)\n",
    "\n",
    "# 简要汇总\n",
    "print(df.describe())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "e0e96798",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   2013-01-01  2013-01-02  2013-01-03  2013-01-04  2013-01-05  2013-01-06\n",
      "A   -1.593051    0.711600   -0.174396    0.125475    0.529611    0.022487\n",
      "B    2.214765    0.492788    1.200618    0.540160    0.157162   -0.105461\n",
      "C    0.835041    0.830289   -0.320375   -0.412453    0.141519    1.160064\n",
      "D    0.310084    1.179015    0.132684    0.325969    0.574031   -0.689046\n"
     ]
    }
   ],
   "source": [
    "# 转置\n",
    "print(df.T)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "fc3c2337",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   D         C         B         A\n",
      "2013-01-01  0.310084  0.835041  2.214765 -1.593051\n",
      "2013-01-02  1.179015  0.830289  0.492788  0.711600\n",
      "2013-01-03  0.132684 -0.320375  1.200618 -0.174396\n",
      "2013-01-04  0.325969 -0.412453  0.540160  0.125475\n",
      "2013-01-05  0.574031  0.141519  0.157162  0.529611\n",
      "2013-01-06 -0.689046  1.160064 -0.105461  0.022487\n",
      "                   A         B         C         D\n",
      "2013-01-06  0.022487 -0.105461  1.160064 -0.689046\n",
      "2013-01-05  0.529611  0.157162  0.141519  0.574031\n",
      "2013-01-02  0.711600  0.492788  0.830289  1.179015\n",
      "2013-01-04  0.125475  0.540160 -0.412453  0.325969\n",
      "2013-01-03 -0.174396  1.200618 -0.320375  0.132684\n",
      "2013-01-01 -1.593051  2.214765  0.835041  0.310084\n"
     ]
    }
   ],
   "source": [
    "# 对列标签降序重排，axis=1是列标签，0是行标签\n",
    "print(df.sort_index(axis=1, ascending=False))\n",
    "\n",
    "# 根据B列升序重排\n",
    "print(df.sort_values(by=\"B\"))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
